package com.eras.shoes.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.os.Bundle
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*

class OptimizedLocationActivity : AppCompatActivity() {
    // 常量定义
    private val TAG = "OptimizedLocation"
    private val LOCATION_PERMISSION_REQUEST_CODE = 1001
    private val LOCATION_TIMEOUT = 30000L // 30秒定位超时
    private val MIN_VALID_LOCATION_AGE = 5 * 60 * 1000L // 5分钟内的位置视为有效
    private val MAX_ACCEPTABLE_ACCURACY = 1000f // 最大可接受的定位精度（米）

    // 定位相关变量
    private lateinit var locationManager: LocationManager
    private var isLocationReceived = false
    private var locationTimeoutJob: kotlinx.coroutines.Job? = null
    private var isLocationRequestActive = false

    // 全局位置存储（根据实际需求修改）
    object GlobalLocation {
        var lat: Double = 0.0
        var lng: Double = 0.0
        var accuracy: Float = 0f
        var updateTime: Long = 0
    }

    // 定位错误类型
    private enum class LocationError {
        PERMISSION_DENIED,
        SERVICE_DISABLED,
        PROVIDER_UNAVAILABLE,
        TIMEOUT,
        NETWORK_ERROR,
        UNKNOWN_ERROR
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 初始化定位管理器
        locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
        // 开始定位流程
        startLocationProcess()
    }

    /**
     * 启动完整的定位流程
     */
    private fun startLocationProcess() {
        // 重置状态
        isLocationReceived = false
        isLocationRequestActive = true

        // 检查权限
        if (checkLocationPermissions()) {
            // 权限已获取，检查定位服务
            if (isLocationServiceEnabled()) {
                // 检查网络（针对网络定位）
                if (isNetworkProviderEnabled() && !isNetworkAvailable()) {
                    handleLocationError(LocationError.NETWORK_ERROR)
                    return
                }

                // 启动定位
                startLocationUpdates()
            } else {
                handleLocationError(LocationError.SERVICE_DISABLED)
            }
        }
    }

    /**
     * 检查定位权限
     */
    private fun checkLocationPermissions(): Boolean {
        // 根据Android版本确定所需权限
        val requiredPermissions = mutableListOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )

        // Android 10及以上需要后台定位权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            requiredPermissions.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
        }

        // 检查未授予的权限
        val permissionsToRequest = requiredPermissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }

        return if (permissionsToRequest.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                permissionsToRequest.toTypedArray(),
                LOCATION_PERMISSION_REQUEST_CODE
            )
            false
        } else {
            true
        }
    }

    /**
     * 检查定位服务是否开启
     */
    private fun isLocationServiceEnabled(): Boolean {
        return try {
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ||
                    locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        } catch (e: Exception) {
            Log.e(TAG, "检查定位服务失败", e)
            false
        }
    }

    /**
     * 检查网络定位是否开启
     */
    private fun isNetworkProviderEnabled(): Boolean {
        return try {
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        } catch (e: Exception) {
            Log.e(TAG, "检查网络定位失败", e)
            false
        }
    }

    /**
     * 检查GPS定位是否开启
     */
    private fun isGpsProviderEnabled(): Boolean {
        return try {
            locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        } catch (e: Exception) {
            Log.e(TAG, "检查GPS定位失败", e)
            false
        }
    }

    /**
     * 检查网络是否可用
     */
    @SuppressLint("MissingPermission")
    private fun isNetworkAvailable(): Boolean {
        val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val network = connectivityManager.activeNetwork ?: return false
            val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
        } else {
            @Suppress("DEPRECATION")
            val networkInfo = connectivityManager.activeNetworkInfo ?: return false
            @Suppress("DEPRECATION")
            networkInfo.isConnected
        }
    }

    /**
     * 启动定位更新
     */
    @SuppressLint("MissingPermission")
    private fun startLocationUpdates() {
        try {
            // 先尝试获取最后已知位置
            val lastKnownLocation = getBestLastKnownLocation()
            lastKnownLocation?.let {
                if (isLocationValid(it)) {
                    handleValidLocation(it, "最后已知位置")
                    isLocationReceived = true
                }
            }

            // 启动定位超时任务
            locationTimeoutJob = CoroutineScope(Dispatchers.Main).launch {
                delay(LOCATION_TIMEOUT)
                if (!isLocationReceived && isLocationRequestActive) {
                    handleLocationError(LocationError.TIMEOUT)
                    stopLocationUpdates()
                }
            }

            // 启动网络定位（如果可用）
            if (isNetworkProviderEnabled()) {
                locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER,
                    5000,   // 5秒间隔
                    5f,     // 5米距离变化
                    networkLocationListener,
                    Looper.getMainLooper()
                )
                Log.d(TAG, "已启动网络定位")
            }

            // 启动GPS定位（如果可用）
            if (isGpsProviderEnabled()) {
                locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    5000,   // 5秒间隔
                    5f,     // 5米距离变化
                    gpsLocationListener,
                    Looper.getMainLooper()
                )
                Log.d(TAG, "已启动GPS定位")
            }

        } catch (e: SecurityException) {
            Log.e(TAG, "定位权限异常", e)
            handleLocationError(LocationError.PERMISSION_DENIED)
        } catch (e: Exception) {
            Log.e(TAG, "启动定位失败", e)
            handleLocationError(LocationError.UNKNOWN_ERROR)
        }
    }

    /**
     * 获取最佳的最后已知位置
     */
    @SuppressLint("MissingPermission")
    private fun getBestLastKnownLocation(): Location? {
        return try {
            val locations = mutableListOf<Location?>()

            // 获取网络定位的最后已知位置
            if (isNetworkProviderEnabled()) {
                locations.add(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER))
            }

            // 获取GPS定位的最后已知位置
            if (isGpsProviderEnabled()) {
                locations.add(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER))
            }

            // 筛选出有效的位置，并选择最新的
            locations
                .filterNotNull()
                .filter { isLocationValid(it) }
                .maxByOrNull { it.time }
        } catch (e: Exception) {
            Log.e(TAG, "获取最后已知位置失败", e)
            null
        }
    }

    /**
     * 验证位置是否有效
     */
    private fun isLocationValid(location: Location): Boolean {
        // 检查位置时间是否在有效期内
        val isRecent = System.currentTimeMillis() - location.time < MIN_VALID_LOCATION_AGE
        // 检查位置精度
        val isAccurateEnough = location.accuracy <= MAX_ACCEPTABLE_ACCURACY
        // 检查经纬度是否有效
        val hasValidCoordinates = location.latitude != 0.0 && location.longitude != 0.0

        return isRecent && isAccurateEnough && hasValidCoordinates
    }

    /**
     * 处理有效的位置信息
     */
    private fun handleValidLocation(location: Location, source: String) {
        // 更新全局位置
        GlobalLocation.lat = location.latitude
        GlobalLocation.lng = location.longitude
        GlobalLocation.accuracy = location.accuracy
        GlobalLocation.updateTime = System.currentTimeMillis()

        // 输出日志
        val locationInfo = String.format(
            Locale.getDefault(),
            "%s:\n纬度: %.6f\n经度: %.6f\n精度: %.1f米\n时间: %s",
            source,
            location.latitude,
            location.longitude,
            location.accuracy,
            Date(location.time).toString()
        )
        Log.d(TAG, locationInfo)
        Toast.makeText(this, locationInfo, Toast.LENGTH_LONG).show()

        // 标记已收到位置，取消超时任务
        isLocationReceived = true
        locationTimeoutJob?.cancel()

        // 这里可以添加后续业务逻辑，如上传位置等
        // processLocation(location)
    }

    /**
     * 停止定位更新
     */
    private fun stopLocationUpdates() {
        try {
            locationManager.removeUpdates(networkLocationListener)
            locationManager.removeUpdates(gpsLocationListener)
            locationTimeoutJob?.cancel()
            isLocationRequestActive = false
            Log.d(TAG, "已停止定位更新")
        } catch (e: Exception) {
            Log.e(TAG, "停止定位更新失败", e)
        }
    }

    /**
     * 处理定位错误
     */
    private fun handleLocationError(error: LocationError) {
        val errorMsg = when (error) {
            LocationError.PERMISSION_DENIED -> "定位权限被拒绝，请在设置中开启"
            LocationError.SERVICE_DISABLED -> "请开启定位服务（设置->位置信息）"
            LocationError.PROVIDER_UNAVAILABLE -> "当前环境无法获取位置，请稍后重试"
            LocationError.TIMEOUT -> "定位超时，请移动到开阔地带重试"
            LocationError.NETWORK_ERROR -> "网络异常，无法使用网络定位"
            LocationError.UNKNOWN_ERROR -> "定位失败，请稍后重试"
        }

        Log.e(TAG, "定位错误: $errorMsg")
        Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show()

        // 根据错误类型引导用户
        when (error) {
            LocationError.PERMISSION_DENIED -> navigateToAppSettings()
            LocationError.SERVICE_DISABLED -> navigateToLocationSettings()
            else -> {}
        }
    }

    /**
     * 导航到应用设置页面
     */
    private fun navigateToAppSettings() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
            data = android.net.Uri.fromParts("package", packageName, null)
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        startActivity(intent)
    }

    /**
     * 导航到系统定位设置页面
     */
    private fun navigateToLocationSettings() {
        val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        startActivity(intent)
    }

    /**
     * 网络定位监听器
     */
    private val networkLocationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            if (isLocationValid(location)) {
                handleValidLocation(location, "网络定位")
            } else {
                Log.w(TAG, "网络定位位置无效，忽略")
            }
        }

        override fun onProviderDisabled(provider: String) {
            Log.w(TAG, "网络定位已关闭")
            if (!isLocationReceived && isGpsProviderEnabled().not()) {
                handleLocationError(LocationError.PROVIDER_UNAVAILABLE)
            }
        }

        override fun onProviderEnabled(provider: String) {
            Log.d(TAG, "网络定位已开启")
            if (!isLocationReceived) {
                startLocationUpdates()
            }
        }

        @Deprecated("Deprecated in Java")
        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
            Log.d(TAG, "网络定位状态变化: $status")
        }
    }

    /**
     * GPS定位监听器
     */
    private val gpsLocationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            if (isLocationValid(location)) {
                handleValidLocation(location, "GPS定位")
            } else {
                Log.w(TAG, "GPS定位位置无效，忽略")
            }
        }

        override fun onProviderDisabled(provider: String) {
            Log.w(TAG, "GPS定位已关闭")
            if (!isLocationReceived && isNetworkProviderEnabled().not()) {
                handleLocationError(LocationError.PROVIDER_UNAVAILABLE)
            }
        }

        override fun onProviderEnabled(provider: String) {
            Log.d(TAG, "GPS定位已开启")
            if (!isLocationReceived) {
                startLocationUpdates()
            }
        }

        @Deprecated("Deprecated in Java")
        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
            Log.d(TAG, "GPS定位状态变化: $status")
        }
    }

    /**
     * 权限请求结果处理
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }

            if (allGranted) {
                // 权限已授予，继续定位流程
                startLocationProcess()
            } else {
                // 检查是否勾选了"不再询问"
                val shouldShowRationale = permissions.any {
                    ActivityCompat.shouldShowRequestPermissionRationale(this, it)
                }

                if (!shouldShowRationale) {
                    // 用户勾选了"不再询问"，引导到设置页面
                    handleLocationError(LocationError.PERMISSION_DENIED)
                } else {
                    // 用户拒绝但未勾选"不再询问"
                    Toast.makeText(this, "需要定位权限才能获取位置信息", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 生命周期管理：在暂停时停止定位
     */
    override fun onPause() {
        super.onPause()
        if (isLocationRequestActive) {
            stopLocationUpdates()
        }
    }

    /**
     * 生命周期管理：在恢复时重新启动定位（如果需要）
     */
    override fun onResume() {
        super.onResume()
        if (!isLocationReceived && !isLocationRequestActive) {
            startLocationProcess()
        }
    }

    /**
     * 生命周期管理：在销毁时确保停止定位
     */
    override fun onDestroy() {
        super.onDestroy()
        stopLocationUpdates()
    }
}

